package com.standard.logcat.provider

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.annotation.RequiresApi
import com.standard.logcat.FloatingWindowImpl
import com.standard.logcat.R
import com.standard.logcat.entity.LogcatItem
import com.standard.logcat.exceptionHandler.UncaughtExceptionHandler
import com.standard.logcat.fps.GetFps
import com.standard.logcat.logBus.LogBus
import com.standard.logcat.sp.ExceptionLogValue
import com.standard.logcat.sp.SP
import java.lang.ref.WeakReference

object Init {
    lateinit var context: Application
    private var num = 0

    private var currentActivity: WeakReference<Activity>? = null


    @RequiresApi(Build.VERSION_CODES.M)
    fun init(context: Application) {
        this.context = context
        registerLifeCircle()
        if (Settings.canDrawOverlays(Init.context)) {
            FloatingWindowImpl(context)
            GetFps.getFps()
            UncaughtExceptionHandler.init()

            if (ExceptionLogValue.exception.isNotEmpty()) {
                LogBus.log.value =
                    LogcatItem(ExceptionLogValue.exception, color = R.color.logcat_red)
                SP().edit().clear().apply()
            }
        }
    }

    /**
     * 获取当前的activity
     */
    fun getActivity(): Activity? = currentActivity?.get()

    /**
     * 注册监听所有activity的生命周期
     * 查看有没有打开悬悬浮窗权限
     */
    private fun registerLifeCircle() {
        context.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {

            @RequiresApi(Build.VERSION_CODES.M)
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

                currentActivity = WeakReference(activity)

                if (num == 0 && !Settings.canDrawOverlays(context)) {
                    num++
                    activity.startActivity(
                        Intent(
                            Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:${context.packageName}")
                        )
                    )
                }
            }

            override fun onActivityStarted(activity: Activity) {}

            override fun onActivityResumed(activity: Activity) {
                LogBus.log.value =
                    LogcatItem("当前页面:\n${activity.localClassName}", color = R.color.logcat_green)
            }

            override fun onActivityPaused(activity: Activity) {}

            override fun onActivityStopped(activity: Activity) {}

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {}
        })
    }
}